package top.ahzy.seobench.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ahzy.seobench.model.dto.MusicSongDto;
import top.ahzy.seobench.result.Result;
import top.ahzy.seobench.service.CommonApiService;
import top.ahzy.seobench.service.MusicService;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MusicServiceImpl implements MusicService {


    @Autowired
    private CommonApiService commonApiService;

    @Override
    public Result searchMp3(String musicName) {
        String html = commonApiService.searchMp3(musicName);
        Document doc = Jsoup.parse(html);
        List<MusicSongDto> musicSongDtoList = parseSongs(doc);
        return Result.success(musicSongDtoList);
    }

    @Override
    public Result getMp3(String musicId) {
        String html = commonApiService.getMp3(musicId);
        Document doc = Jsoup.parse(html);
        MusicSongDto mp3DownloadUrl = getMp3DownloadUrl(doc);
        return Result.success(mp3DownloadUrl);
    }

    private List<MusicSongDto> parseSongs(Document doc) {
        List<MusicSongDto> musicSongDtoList = new ArrayList<>();

        // 选择所有歌曲行 - 根据HTML结构，每个歌曲都在class="row"的div中
        Elements songRows = doc.select("div.card-body div.row:has(a.music-link)");

        for (Element row : songRows) {
            // 提取歌曲名
            String title = row.select("span.music-title span").first().text();

            // 提取歌手名
            String artist = row.select("small.text-jade").first().text();

            // 提取播放链接
            String playUrl = row.select("div.col-4 a").attr("href");
            playUrl = playUrl.replace("/music/", "");

            MusicSongDto musicSongDto = new MusicSongDto();
            musicSongDto.setTitle(title);
            musicSongDto.setArtist(artist);
            musicSongDto.setMusicId(playUrl);
            musicSongDtoList.add(musicSongDto);
        }

        return musicSongDtoList;
    }

    private  MusicSongDto getMp3DownloadUrl(Document doc) {
        String mp3UrlKey = "";
        MusicSongDto dto = new MusicSongDto();

        // 提取歌曲信息
        String title = extractTitle(doc);
        String artist = extractArtist(doc);
        String coverUrl = extractCoverUrl(doc);
        String duration = extractDuration(doc);
        String lrcContent = extractLyrics(doc);
        String mp3Url = extractMp3Url(doc);

        dto.setMp3Url(mp3Url);
        dto.setCoverUrl(coverUrl);
        dto.setLrcContent(lrcContent);
        dto.setTitle(title);
        dto.setArtist(artist);


//        String json = commonApiService.getMp3Url(mp3UrlKey);
//        JSONObject res = JSONUtil.parseObj(json);
//        if(res.containsKey("code") && res.getInt("code") == 1) {
//            return res.getJSONObject("data").getStr("url");
//        }

        return dto;
    }


    // 获取音乐播放地址
    private String extractMp3Url(Document doc) {
        String mp3UrlKey = "";

        // 方法1：直接从script标签中提取（更可靠）
        Elements scripts = doc.select("script");
        for (Element script : scripts) {
            String scriptContent = script.html();
            if (scriptContent.contains("play_id")) {
                // 使用正则表达式匹配play_id
                String pattern = "\"play_id\"\\s*:\\s*\"([^\"]+)\"";
                java.util.regex.Pattern r = java.util.regex.Pattern.compile(pattern);
                java.util.regex.Matcher m = r.matcher(scriptContent);
                if (m.find()) {
                    mp3UrlKey = m.group(1);
                }
            }
        }

        // 方法2：从JavaScript变量中提取（备用方法）
        if (StrUtil.isEmpty(mp3UrlKey)) {
            String pattern = "play_id\":\"([^\"]+)\"";
            String html = doc.html();
            java.util.regex.Pattern r = java.util.regex.Pattern.compile(pattern);
            java.util.regex.Matcher m = r.matcher(html);
            if (m.find()) {
                mp3UrlKey = m.group(1);
            }
        }

        if (StrUtil.isEmpty(mp3UrlKey)) {
            return mp3UrlKey;
        }

        String json = commonApiService.getMp3Url(mp3UrlKey);
        JSONObject res = JSONUtil.parseObj(json);
        if(res.containsKey("code") && res.getInt("code") == 1) {
            return res.getJSONObject("data").getStr("url");
        }

        return mp3UrlKey;
    }

    private  String extractTitle(Document doc) {
        // 从 <h1 class="badge badge-light-green"> 提取标题
        Element titleElement = doc.selectFirst("h1.badge-light-green");
        return titleElement != null ? titleElement.text() : "";
    }

    private  String extractArtist(Document doc) {
        // 标题中包含艺术家信息，格式为"歌曲名 - 艺术家"
        String fullTitle = extractTitle(doc);
        if (fullTitle.contains("-")) {
            return fullTitle.split("-")[1].trim();
        }
        return "";
    }

    private  String extractCoverUrl(Document doc) {
        // 从 <img> 标签提取封面URL
        Element imgElement = doc.selectFirst("#aplayer img");
        return imgElement != null ? imgElement.attr("src") : "";
    }

    // 获取音乐时长
    private  String extractDuration(Document doc) {
        // 从JavaScript变量中提取时长
        String scriptContent = doc.select("script[type=text/javascript]").html();
        if (scriptContent.contains("mp3_duration")) {
            String[] parts = scriptContent.split("mp3_duration\":\"");
            if (parts.length > 1) {
                return parts[1].split("\"")[0];
            }
        }
        return "";
    }

    private  String extractLyrics(Document doc) {
        // 从隐藏的歌词div中提取歌词
        Element lrcElement = doc.selectFirst("div.content-lrc");
        return lrcElement != null ? lrcElement.text() : "";
    }
}
